<template>
	<uni-loading v-if="loading"></uni-loading>
	<view class="body" v-else>
		<view class="top-container" style="height: 44px;">
			<!-- #ifdef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `8px`}"> -->
			<!-- #endif -->
			<!-- #ifndef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `52px`}"> -->
			<!-- #endif -->
			<view class="top-container-inner">
				<uni-list :border="false">
					<uni-list-item :border="false" title="汇总重量" :rightText="totalWeight" />
				</uni-list>
			</view>
		</view>
		<!--  列表  -->
		<template v-if="purchaseList && purchaseList.length > 0">
			<uni-swipe-action>
				<uni-swipe-action-item :left-options="options" @click="handleDelete(item)" v-for="item in purchaseList">
					<view class="panel" @click="openDetail(item)">
						<view class="panel_title" :class="{error: item.error}">
							<view class="panel_title_left">{{ item.materialName }}</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料编码：</view>
									<view class="panel_content_row_item_value">{{ item.materialNo }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">规格：</view>
									<view class="panel_content_row_item_value">{{ item.materialSpec }}</view>
								</view>
							</view>
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">批次：</view>
									<view class="panel_content_row_item_value">{{ item.batchNo }}</view>
								</view>
							</view>
						</view>
						<view class="panel_dashboard">
							<view class="panel_dashboard_item">
								<view class="panel_dashboard_item_number success">{{ item.boxCount || 0 }}</view>
								<view class="panel_dashboard_item_value">总箱数</view>
							</view>
							<view class="panel_dashboard_item">
								<view class="panel_dashboard_item_number default">{{ item.count || 0 }}{{item.unit}}
								</view>
								<view class="panel_dashboard_item_value">总重量</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</template>
		<uni-empty-info v-else label="暂无物料信息"></uni-empty-info>

		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="handleChoose" class="footerBtn reset"><i class="iconfont icon-duihao btn_icon"></i>选择
				</button>
				<button @click="handleWarehousing" class="footerBtn save"><i
						class="iconfont icon-shengchenggongdan btn_icon"></i>创建退料订单
				</button>
				<button @click="handleScanCode" class="footerBtn scan" type="primary"><i
						class="iconfont icon-saomiao btn_icon"></i>扫码
				</button>
			</view>
		</view>

		<!-- 弹出层 -->
		<ScaningPopup ref="scaningPopup" :defaultStock="false" :isLocation="false" title="生产领料单退料" type="taskRefund"
			@success="initData">
		</ScaningPopup>

		<!-- 级联选择 -->
		<CascadePicker class="picker-view" ref="pickerView" popupTitle="选择物料信息" :map="{text:'materialName',value:'id'}"
			:refresherEnabled="false" @change="onchange" :loading="pickerLoading" :showSearch="false"
			:multi-select="true" showNameOnly showMaterialDetail checkCount>
		</CascadePicker>
	</view>
</template>
<script>
	import uniLoading from "../../vBase/components/uni-loading/uni-loading"
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
	import ScaningPopup from "@/components/popup/materialPopup.vue"
	import CascadePicker from '../../components/cascade-picker/cascade-picker-view.vue'
	import CascadePickerJs from '../../components/cascade-picker/cascade-picker.js'

	export default {
		components: {
			uniLoading,
			uniEmptyInfo,
			ScaningPopup,
			CascadePicker,
		},
		mixins: [CascadePickerJs],
		data() {
			return {
				loading: true,
				purchaseList: [],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF4E74'
					}
				}],
				scaningShow: false,
				scanNo: null,
				isFouce: false,
				stockList: [],
				stockNo: '',
				outBoxNo: null,
				idList: null,
				produceHouse: '',
				materialBomBillNo: '',
				taskBillNo: '',

				// 级联查询
				boxList: [],
				dataTree: [],
				pickerLoading: true,
				
				totalWeight: "0jin"
			}
		},
		async onLoad(e) {
			if (e.materialBomBillNo) this.materialBomBillNo = e.materialBomBillNo
			if (e.taskBillNo) this.taskBillNo = e.taskBillNo
			if (e.produceHouse) this.produceHouse = e.produceHouse
			this.initData()
		},
		onUnload() {
			uni.$off('deleteItem');
		},
		mounted() {
			let self = this
			uni.$on('deleteItem', ({
				material,
				success
			}) => {
				uni.showModal({
					title: '提示',
					content: '确认删除吗？',
					success(res) {
						if (res.confirm) {
							const {
								id,
								stockNo,
								materialNo,
								boxNo
							} = material;
							self.$api.deleteUserMaterialBomReturnMaterialBox({
								id: material.id
							}, {
								loading: true
							}).then((res) => {
								if (!res.res) return;
								self.initData();
								success && success();
							});
						}
					}
				})
			})
		},
		methods: {
			/** 初始化数据 */
			initData() {
				this.pageConfig = {
					pageIndex: 0,
					pageSize: 20,
					bottomEnd: false,
					bottomLoading: true
				}
				this.getPurchaseList()
			},

			/**
			 * 查看详情
			 */
			async openDetail(material) {
				const {
					id,
					stockNo,
					batchNo,
					materialName,
					materialNo
				} = material
				let {
					res,
					data = []
				} = await this.$api.getUserMaterialBomReturnMaterialBox({
					_detailId: id,
				}, {
					loading: true
				});
				let dataList = data.map(item => {
					return {
						id: item.id,
						materialName,
						materialNo,
						stockNo,
						batchNo,
						boxNo: item.boxNo,
						count: item.count,
						unit: item.unit,
					}
				})
				this.openPopNVue('退料明细', dataList, null, this.outBoxNo ?? [])
			},

			/** 获取数据 */
			async getPurchaseList() {
				let {
					res,
					data = []
				} = await this.$api.getUserMaterialBomReturnMaterial();
				if (!res) return;
				if (this.idList && this.idList.length > 0) {
					this.idList.forEach((item) => {
						let index = data.findIndex((element) => {
							return element.id === item
						})
						if (index > -1) {
							data[index].error = true
						}
					})
				}
				this.purchaseList = data;
				this.loading = false;
				this.pageConfig.bottomEnd = true;
				this.pageConfig.bottomLoading = false;
				uni.stopPullDownRefresh();
				this.handleWeightTotal();
			},
			
			/**
			 * 计算总重量
			 */
			handleWeightTotal() {
				if (!this.purchaseList || !this.purchaseList.length) {
					this.totalWeight = "0"
					return
				}
				let num = 0
				this.purchaseList.forEach(v => {
					if (v.count) {
						num += v.count
					}
				})
				this.totalWeight = num.toString()
			},

			/**
			 * 选择
			 */
			async handleChoose() {
				try {
					const res = await this.$api.getProduceReturnList({
						taskBillNo: this.taskBillNo
					})
					if (!res.res) return
					this.dataTree = res.data ?? []
					let tree = JSON.parse(JSON.stringify(this.dataTree))
					tree.map(v => {
						return Object.assign(v, {
							maxCount: v.count 
						})
					})
					this.$refs.pickerView.updateData({
						treeData: tree,
						selected: [],
						selectedIndex: 0
					})
				} finally {
					this.pickerLoading = false
					this.$forceUpdate()
				}
			},

			/** 立即入库 */
			handleWarehousing() {
				const {
					stockNo,
					purchaseList
				} = this;
				if (!purchaseList || !purchaseList.length) {
					uni.showToast({
						title: '请扫码添加物料',
						icon: 'none'
					});
					return;
				}
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否创建退料订单？',
					success(res) {
						if (res.confirm) {
							self.$api.createMaterialBomReturnBill({
								taskBillNo: self.taskBillNo,
								materialBomBillNo: self.materialBomBillNo,
								produceHouse: self.produceHouse
							}).then(res => {
								if (res.res) {
									if (res.outBoxNo && res.outBoxNo.length > 0) {
										self.outBoxNo = res.outBoxNo
										self.idList = res.idList
										uni.showToast({
											title: '存在已出库箱号',
											icon: 'none'
										})
									} else {
										uni.showToast({
											title: '操作成功',
											icon: 'none'
										})
									}
									self.initData();
								}
							})
						}
					}
				})
			},

			/**
			 * 选择仓库
			 * @param e
			 */
			stockChange(e) {
				this.stockNo = this.stockList[e].stockNo
				this.initData()
			},

			/** 扫码 */
			async handleScanCode() {
				this.$refs.scaningPopup.open(this.stockNo, null, this.materialBomBillNo, this.taskBillNo)
			},

			/**
			 * 删除物料
			 * @param {Object} e
			 */
			handleDelete(material) {
				const {
					stockNo,
					materialNo,
					batchNo,
					exp
				} = material
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否删除物料？',
					success(res) {
						if (res.confirm) {
							self.$api.deleteUserMaterialBomReturnMaterial({
								id: material.id
							}, {
								loading: true
							}).then(res => {
								if (res.res) {
									uni.showToast({
										title: '物料删除成功',
										icon: 'none'
									})
									self.initData();
								}
							})
						}
					}
				})
			},

			/**
			 * 下拉刷新数据
			 */
			onPullDownRefresh() {
				this.initData()
			},

			/**
			 * 加到退料表
			 * @param {Object} e
			 */
			async onchange(e) {
				try {
					this.boxList = JSON.parse(JSON.stringify(e))
					this.boxList.forEach(option => {
						option.count = Number(option.count ?? 0)
					})
					let res = await this.$api.addMaterialBomBoxReturn({
						boxList: e,
						taskBillNo: this.taskBillNo,
						materialBomBillNo: this.materialBomBillNo
					})
					if (!res.res) return
					uni.showToast({
						title: "添加成功",
						icon: "none"
					})
					this.initData();
				} finally {}
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.error {
		color: red;
	}

	.save {
		width: 140px !important;
	}
</style>
